<!--
 * @Date: 2022-03-26 20:20:29
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-04-18 22:15:03
 * @FilePath: \weibovue\src\components\chooseCity\chooseCity.vue
 * @Description: 日期选择组件
-->
<template>
  <el-popover
    placement="top-start"
    v-model:visible="visible"
    :width="500"
    trigger="click"
    @before-leave="popoverClose"
  >
    <template #reference>
      <div class="result" @click="visible = !visible">
        <div class="resText">
          {{ cityRes ? cityRes : result }}
          <i
            class="iconfont icon-jiantou_yemian_xiangxia"
            :class="visible ? 'rotate' : 'noRotate'"
          ></i>
        </div>
      </div>
    </template>
    <div class="container">
      <el-row>
        <el-col :span="10">
          <el-radio-group v-model="radioVal" size="default">
            <el-radio-button label="按城市"></el-radio-button>
            <el-radio-button label="按省份"></el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="10" :offset="3">
          <el-select
            placeholder="搜索城市"
            size="default"
            v-model="selectVal"
            filterable
            :filter-method="filterMethod"
            @change="selectChange"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <!-- 城市字母 -->
      <template v-if="radioVal === '按城市'">
        <div class="cityChar">
          <div
            class="citiesItem"
            :class="[index === activeIdx ? 'active' : '']"
            v-for="(item, index) in Object.keys(cities)"
            :key="index"
            @click="clickCharItem(item, index)"
          >
            {{ item }}
          </div>
        </div>
        <el-scrollbar max-height="300px">
          <template v-for="(value, key) in cities" :key="key">
            <el-row style="margin-bottom: 10px">
              <el-col :span="2" :id="key">{{ key }}:</el-col>
              <el-col :span="22" class="city">
                <div
                  class="cityName"
                  v-for="(item, index) in value"
                  :key="item.id"
                  @click="clickCityChar(item, index)"
                >
                  {{ item.name }}
                </div>
              </el-col>
            </el-row>
          </template>
        </el-scrollbar>
      </template>
      <!-- 省份 -->
      <template v-else>
        <div class="provinceChar">
          <div
            class="citiesItem"
            :class="[index === activeIdx ? 'active' : '']"
            v-for="(item, index) in Object.keys(provinces)"
            :key="index"
            @click="clickCharItem(item, index)"
          >
            {{ item }}
          </div>
        </div>
        <el-scrollbar max-height="300px">
          <template v-for="(value, key) in provinces" :key="key">
            <el-row style="margin-bottom: 10px">
              <el-col :span="3" :id="key" style="font-size: 14px"
                >{{ value[0].name }}:</el-col
              >
              <el-col :span="21" class="city">
                <div
                  class="provinceName"
                  v-for="(item, index) in value[0].data"
                  :key="index"
                  @click="clickProvince(item, index)"
                >
                  {{ item }}
                </div>
              </el-col>
            </el-row>
          </template>
        </el-scrollbar>
      </template>
    </div>
  </el-popover>
</template>
<script lang="ts" setup>
import { ref, watch, onMounted, PropType } from "vue";
import city from "./lib/city";
import province from "./lib/province.json";
import { City } from "./type";
//最终结果
let result = ref<string>("请选择");
let visible = ref<boolean>(false);
let radioVal = ref<string>("按城市");
let selectVal = ref<string>("");
let cities = ref(city.cities);
let provinces = ref(province);
let activeIdx = ref<number | null>(null);
let preDom = ref<HTMLElement>();
//重置选择
const resetResult = () => {
  result.value = "请选择";
};
const props = defineProps({
  cityRes: {
    type: String,
  },
});
const emits = defineEmits(["changeCity", "changProvince"]);
const options = ref<City[]>([]);
//点击字母回调
const clickCharItem = (item: any, index: number) => {
  if (preDom.value) {
    preDom.value.style.color = "#000";
  }
  activeIdx.value = index;
  let elID = document.getElementById(item);
  if (elID) {
    preDom.value = elID;
    elID.scrollIntoView({
      behavior: "smooth", // 平滑过渡
      block: "start", // 上边框与视窗顶部平齐。默认值
    });
    elID.style.color = "#409eff";
  }
};
//弹出框关闭的回调
const popoverClose = () => {
  activeIdx.value = null;
};
//点击城市文字
const clickCityChar = (item: City, index: number) => {
  result.value = item.name;
  visible.value = false;
  emits("changeCity", item);
};
//点击省份文字
const clickProvince = (item: any, index: number) => {
  result.value = item;
  visible.value = false;
  emits("changeCity", item);
};
//自定义过滤
const filterMethod = (val: string) => {
  let values = Object.values(cities.value).flat(2);
  if (val === "") {
    options.value = values;
  } else {
    if (radioVal.value === "按城市") {
      //汉字加拼音过滤
      options.value = values.filter((item) => {
        return item.name.includes(val) || item.spell.includes(val);
      });
    } else {
      //汉字过滤
      options.value = values.filter((item) => {
        return item.name.includes(val);
      });
    }
  }
};
//下拉框选中改变回调
const selectChange = (val: number) => {
  const selectCity = options.value.find((item) => item.id === val);
  result.value = selectCity!.name;
  if (radioVal.value === "按城市") {
    emits("changeCity", selectCity);
  } else {
    emits("changProvince", selectCity!.name);
  }
  visible.value = false;
};
//分发方法
defineExpose({
  resetResult,
});
onMounted(() => {
  //扁平cities数组
  // console.log(props.cityRes);
  options.value = Object.values(cities.value).flat(2);
  if (props.cityRes) {
    // console.log('更新了结果');

    result.value = props.cityRes;
  }
});
watch(
  () => radioVal.value,
  (val) => {
    activeIdx.value = null;
    preDom.value = undefined;
    selectVal.value = "";
  },
);
</script>
<style lang="less" scoped>
.rotate {
  display: inline-block; /*重点在这儿，盒模型，block*/
  transform: rotate(180deg);
}
.noRotate {
  display: inline-block; /*重点在这儿，盒模型，block*/
  transform: rotate(0deg);
}
.result {
  display: flex;
  align-items: center;
  width: fit-content;
  cursor: pointer;
  .iconfont {
    position: relative;
    top: 2px;
    margin-left: 4px;
    transition: all 0.25s linear;
  }
  .resText {
    border: 1px solid #ccc;
    padding: 0 10px;
    border-radius: 10px;
  }
}
.container {
  padding: 0 20px;
  margin-top: 5px;
  .cityChar,
  .provinceChar {
    display: flex;
    flex-wrap: wrap;
    margin-top: 5px;

    .citiesItem {
      padding: 2px 6px;
      margin-right: 5px;
      margin-bottom: 5px;
      border: 1px solid #eee;
      cursor: pointer;
      font-size: 14px;
    }
  }
  .cityArea {
    transition: all 0.5s linear;
  }
  .city {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .cityName,
    .provinceName {
      margin-right: 6px;
      margin-bottom: 6px;
      cursor: pointer;
      font-size: 14px;
    }
  }
}
.active {
  background-color: #409eff;
  color: #fff;
}
</style>
